package com.artron.mediaartron.ui.fragment.center;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.design.widget.BottomSheetDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.image.ImageUtils;
import com.artron.baselib.utils.UIUtils;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.Address;
import com.artron.mediaartron.data.entity.LoginData;
import com.artron.mediaartron.data.entity.UploadIcon;
import com.artron.mediaartron.data.entity.User;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.data.task.AddressTask;
import com.artron.mediaartron.data.task.UserIconUploadTask;
import com.artron.mediaartron.ui.helper.ThrottleFirstClickHelper;
import com.bigkoo.pickerview.OptionsPickerView;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.functions.Action1;

import static android.app.Activity.RESULT_OK;

public class UserInfoFragment extends BaseStaticFragment implements View.OnClickListener {

    public static final String USER_NAME = "UserName";
    public static final String PERSONALIZED = "PersonalizedSignature";
    public static final String GENDER = "Gender";
    public static final String BIRTHDAY = "Birthday";
    public static final String USER_ICON = "UserIcon";
    public static final String CITY = "City";

    public static final int REQUEST_ALBUM = 2000;
    public static final int REQUEST_CROP = 3000;
    public static final String IMAGE_UNSPECIFIED = "image/*";

    @BindView(R.id.UserInfoFragment_rl_user_icon)
    protected RelativeLayout mRlUserIcon;
    @BindView(R.id.UserInfoFragment_iv_user_icon)
    protected ImageView mIvUserIcon;
    @BindView(R.id.UserInfoFragment_et_user_name)
    protected EditText mEtUserName;
    @BindView(R.id.UserInfoFragment_rl_user_name)
    protected RelativeLayout mRlUserName;
    @BindView(R.id.UserInfoFragment_et_personalized_signature)
    protected EditText mEtPersonalizedSignature;
    @BindView(R.id.UserInfoFragment_rl_personalized_signature)
    protected RelativeLayout mRlPersonalizedSignature;
    @BindView(R.id.UserInfoFragment_tv_gender)
    protected TextView mTvGender;
    @BindView(R.id.UserInfoFragment_rl_gender)
    protected RelativeLayout mRlGender;
    @BindView(R.id.UserInfoFragment_tv_birthday)
    protected TextView mTvBirthday;
    @BindView(R.id.UserInfoFragment_rl_birthday)
    protected RelativeLayout mRlBirthday;
    @BindView(R.id.UserInfoFragment_tv_city)
    protected TextView mTvCity;
    @BindView(R.id.UserInfoFragment_rl_city)
    protected RelativeLayout mRlCity;
    private BottomSheetDialog mSexBottomSheetDialog;
    private DatePickerDialog mDatePickerDialog;
    public OptionsPickerView mPvOptions;
    private Address mAddress;
    private File mImageFile;
    private LoginData mLoginData;
    private int[] mPositionArr;

    public static UserInfoFragment newInstance(LoginData data) {
        UserInfoFragment fragment = new UserInfoFragment();
        fragment.init(data);
        return fragment;
    }

    private void init(LoginData data) {
        mLoginData = data;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_user_info;
    }

    @Override
    protected void initVariable() {
        AddressTask.getAddress(mContext, new Action1<Address>() {
            @Override
            public void call(Address address) {
                mAddress = address;
            }
        });
    }

    @Override
    protected void initView() {
        mRlUserName.setOnClickListener(this);
        mRlPersonalizedSignature.setOnClickListener(this);
        mRlGender.setOnClickListener(this);
        ThrottleFirstClickHelper.throttleFirst(mRlUserIcon, this);
        ThrottleFirstClickHelper.throttleFirst(mRlBirthday, this);
        ThrottleFirstClickHelper.throttleFirst(mRlCity, this);

        initSexBottomSheetDialog();
        initDataPicker();
        initAddressPicker();

        if (!TextUtils.isEmpty(mLoginData.getPhotoUrl())) {
            ImageUtils.setCircleUrl(mIvUserIcon, mLoginData.getPhotoUrl());
        }
        mEtUserName.setText(mLoginData.getNickname());
        mEtPersonalizedSignature.setText(mLoginData.getSignature());
        String gender;
        if ("1".equals(mLoginData.getSex())) {
            gender = "男";
        } else {
            gender = "女";
        }

        mTvGender.setText(gender);
        mTvBirthday.setText(mLoginData.getBirthday());
        String address = String.format("%s-%s-%s", mLoginData.getProvinceName(), mLoginData.getCityName(),
                mLoginData.getCountyName());
        mTvCity.setText(address);
    }

    private void initAddressPicker() {
        AddressTask.getAddress(mContext, new Action1<Address>() {

            @Override
            public void call(Address address) {
                mAddress = address;

                final List<Address.Province> provinces = AddressTask.getProvinces(mAddress);
                final List<List<Address.City>> cities = AddressTask.getCities(provinces);
                final List<List<List<Address.District>>> districts = AddressTask.getDistricts(provinces);

                //返回的分别是三个级别的选中位置
                mPvOptions = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        mPositionArr = new int[]{options1, options2, options3};

                        String tx = provinces.get(options1).getPickerViewText() + "-" +
                                cities.get(options1).get(options2).getPickerViewText() + "-" +
                                districts.get(options1).get(options2).get(options3).getPickerViewText();
                        mTvCity.setText(tx);
                    }
                })
                        .setTitleText("城市选择")
                        .build();
                mPvOptions.setPicker(provinces, cities, districts);
            }
        });
    }

    private void selectAlbum() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
        startActivityForResult(albumIntent, REQUEST_ALBUM);
    }

    private void cropImage(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mImageFile));
        startActivityForResult(intent, REQUEST_CROP);
    }

    private void initDataPicker() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        final int day = calendar.get(Calendar.DAY_OF_MONTH);
        mDatePickerDialog = new DatePickerDialog(mContext, android.R.style.Theme_DeviceDefault_Light_Dialog,
                new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                mTvBirthday.setText(String.format("%d年%d月%d日", year, month + 1, dayOfMonth));
            }
        }, year, month, day);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK != resultCode) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ALBUM:
                createImageFile();
                if (!mImageFile.exists()) {
                    return;
                }

                Uri uri = data.getData();
                if (uri != null) {
                    cropImage(uri);
                }
                break;

            case REQUEST_CROP:
                ImageUtils.setCircleUrl(mIvUserIcon, mImageFile.getAbsolutePath());
                break;
        }
    }

    private void createImageFile() {
        mImageFile = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
        try {
            mImageFile.createNewFile();
        } catch (IOException e) {
            Log.e(TAG, "createImageFile: ", e);
            MobclickAgent.reportError(UIUtils.getContext(), e);
        }
    }

    private void initSexBottomSheetDialog() {
        mSexBottomSheetDialog = new BottomSheetDialog(mContext);
        mSexBottomSheetDialog.setContentView(R.layout.layout_bottom_add_shopping_cart_or_buy);
        bindDataAndListener(R.id.ItemBottomAddVideo_tv_add_shopping_cart, "男");
        bindDataAndListener(R.id.ItemBottomAddVideo_tv_buy, "女");
        bindDataAndListener(R.id.ItemBottomAddVideo_tv_cancel, "取消");
        mSexBottomSheetDialog.getDelegate()
                .findViewById(android.support.design.R.id.design_bottom_sheet)
                .setBackgroundResource(android.R.color.transparent);
    }

    private void bindDataAndListener(int id, String sex) {
        TextView man = (TextView) mSexBottomSheetDialog.findViewById(id);
        assert man != null;
        man.setText(sex);
        man.setTextColor(Color.BLACK);
        man.setOnClickListener(this);
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.UserInfoFragment_rl_user_name:
                mEtUserName.requestFocus();
                break;
            case R.id.UserInfoFragment_rl_personalized_signature:
                mEtPersonalizedSignature.requestFocus();
                break;
            case R.id.UserInfoFragment_rl_user_icon://更换头像
                selectAlbum();
                break;
            case R.id.UserInfoFragment_rl_gender://修改性别
                mSexBottomSheetDialog.show();
                break;
            case R.id.UserInfoFragment_rl_birthday://出生年月
                mDatePickerDialog.show();
                break;
            case R.id.UserInfoFragment_rl_city://所在城市
                if (mPvOptions != null) {
                    mPvOptions.show();
                }
                break;
            case R.id.ItemBottomAddVideo_tv_add_shopping_cart://性别:男
                mTvGender.setText("男");
                mSexBottomSheetDialog.dismiss();
                break;
            case R.id.ItemBottomAddVideo_tv_buy://性别:女
                mTvGender.setText("女");
                mSexBottomSheetDialog.dismiss();
                break;
            case R.id.ItemBottomAddVideo_tv_cancel://性别:取消选择
                mSexBottomSheetDialog.dismiss();
                break;
        }
    }


    @Override
    public boolean onBackPressed() {
        String userName = mEtUserName.getText().toString().trim();
        String personalizedSignature = mEtPersonalizedSignature.getText().toString().trim();
        String gender = mTvGender.getText().toString().trim();
        if ("男".equals(gender)) {
            gender = "1";
        } else {
            gender = "2";
        }
        String birthday = mTvBirthday.getText().toString().trim();
        String city = mTvCity.getText().toString().trim();
        Intent intent = new Intent();
        intent.putExtra(USER_NAME, userName);
        intent.putExtra(PERSONALIZED, personalizedSignature);
        intent.putExtra(GENDER, gender);
        intent.putExtra(BIRTHDAY, birthday);
        intent.putExtra(CITY, city);

        //长传图片
        String token = AppProfile.getUserInfo().getUser().getUtoken();
        if (mImageFile != null) {
            intent.putExtra(USER_ICON, mImageFile.getAbsolutePath());
            UserIconUploadTask.uploadUserIcon(token, mImageFile.getAbsolutePath(), new Action1<Response<UploadIcon>>() {
                @Override
                public void call(Response<UploadIcon> response) {
                    Log.d(TAG, "call: " + response);
                    if (response.getData() != null) {
                        String photoUrl = response.getData().getPhotoUrl();
                        mLoginData.setPhotoUrl(photoUrl);
                        AppProfile.getUserInfo().update(mLoginData);
                    }
                }
            });
        }
        getActivity().setResult(RESULT_OK, intent);
        //上传用户数据
        String provinceId, cityId, districtId;

        if (mPositionArr != null) {
            Address.Province province = mAddress.getProvinces().get(mPositionArr[0]);
            provinceId = province.getPid() + "";
            Address.City cityD = province.getCityList().get(mPositionArr[1]);
            cityId = cityD.getPid() + "";
            Address.District district = cityD.getDistricts().get(mPositionArr[2]);
            districtId = district.getPid() + "";
        } else {
            User user = AppProfile.getUserInfo().getUser();
            provinceId = user.getProvinceCode();
            cityId = user.getCityCode();
            districtId = user.getCountyCode();
        }


        Observable<Response> api = RetrofitHelper.getLoginApi().modifyUserInfo(token, userName, gender, birthday,
                provinceId, cityId, districtId, personalizedSignature);
        RetrofitHelper.subscript(api, new Action1<Response>() {
            @Override
            public void call(Response response) {
                Log.d(TAG, "call: " + response);
            }
        });
        return super.onBackPressed();
    }
}
